package sing.core.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class EncryptUtil {

    public static String hmacSha1(String key, String datas) {
        String cipher = "";
        try {
            try {
                byte[] data = key.getBytes(StandardCharsets.UTF_8);
                //根据给定的字节数组构造一个密钥，第二个参数指定一个密钥的算法名称，生成HmacSHA1专属密钥
                SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");

                //生成一个指定Mac算法的Mac对象
                Mac mac = Mac.getInstance("HmacSHA1");
                //用给定密钥初始化Mac对象
                mac.init(secretKey);
                byte[] text = datas.getBytes(StandardCharsets.UTF_8);
                byte[] encryptByte = mac.doFinal(text);
                cipher = bytesToHexStr(encryptByte);
            } catch (NoSuchAlgorithmException | InvalidKeyException e) {
                cipher = "";
            }
        } catch (Exception e) {
            cipher = "";
        }

        return cipher;
    }

    public static String getMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();

            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++) {
                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }
            return strBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    /**
     * byte数组转16进制字符串
     *
     * @param bytes byte数组
     * @return hex字符串
     */
    public static String bytesToHexStr(byte[] bytes) {
        StringBuilder hexStr = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            hexStr.append(hex);
        }
        return hexStr.toString();
    }
}
